package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveByDto(dishDto);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();

        //不够优雅
//        if (name!=null && name.length()>0){
//            wrapper.like(Dish::getName,name);
//        }

        //也不够优雅
//        wrapper.like((name!=null && name.length()>0),Dish::getName,name);

        //优雅！
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);

        dishService.page(pageInfo, wrapper);

        //DtoPage 里现在没有 records以外  所有数据都有了
        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        //现在要做的  是   dishDtoPage中的 List<records> 补满（包括categoryName）
        List<DishDto> dtoRecords = new ArrayList<>();

        //遍历dish的 records集合
        List<Dish> pageRecords = pageInfo.getRecords();

        for (Dish dish : pageRecords) {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(dish, dishDto);

            Category category = categoryService.getById(dish.getCategoryId());

            dishDto.setCategoryName(category.getName());

            dtoRecords.add(dishDto);
        }

        dishDtoPage.setRecords(dtoRecords);

        return R.success(dishDtoPage);
    }


    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public R<Dish> getById(@PathVariable Long id) {

        DishDto dto = dishService.getByIdRDto(id);

        return R.success(dto);
    }

    //根据菜品分类id 查询菜品列表信息
    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId, Integer status) {//Dish dish

        log.info("查看需要查询的菜品分类id:" + categoryId);

        String key = "dish_" + categoryId;//键怎么起名字 dish_川菜分类id  dish_湘菜分类id
        List<DishDto> redisDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        log.info("从redis中取出的集合:" + redisDtoList);
        if (redisDtoList != null) {//redis里有数据
            log.info("菜品数据是从 redis取出来的。。。。不用查询数据库了");
            return R.success(redisDtoList);
        }


        // 如果没查到 去数据库查


        // select * from dish where category_id=?
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, categoryId);
        //拼一个wrapper条件
        wrapper.eq(status != null, Dish::getStatus, status);
        List<Dish> dishList = dishService.list(wrapper);
        // dish没有口味信息  前端没有展示 口味
        // 需要返回带口味 dishdto
        List<DishDto> dishDtoList = new ArrayList<>();
        //  List<Dish> dishList===> List<DishDto> dishDtoList
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            //再加入相关的菜品口味数据
            // 根据菜品的id
            Long dishId = dishDto.getId();
            // select * from dish_flavor where dish_id=?
            LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavors = dishFlavorService.list(wrapper1);
            //存到 dishdto中
            dishDto.setFlavors(flavors);
            //存到集合中
            dishDtoList.add(dishDto);
        }
// redis没数据  查询了数据 得到最后数据  dishDtoList
        // 再把 查到的存到redis中
        redisTemplate.opsForValue().set(key, dishDtoList);

        return R.success(dishDtoList);
    }


    /**
     * 修改菜品
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateByDto(dishDto);

        return R.success("修改成功");
    }


    /**
     * 停售、起售
     */
    @PostMapping("/status/{flag}")
    public R<String> stopAndRun(@PathVariable Integer flag, Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            DishDto dto = dishService.getByIdRDto(ids[i]);

            if (flag == 0) {
                dto.setStatus(0);
            } else if (flag == 1) {
                dto.setStatus(1);
            } else {
                return R.error("状态信息错误");
            }

            dishService.updateByDto(dto);
        }
        return R.success("修改成功");
    }

    /**
     * 删除
     */
    @DeleteMapping
    public R<String> delete(Long[] ids) {
        for (Long id : ids) {
            dishService.removeAllInfoById(id);
        }

        return R.success("删除成功");
    }
}
